import socket,time
import sys
from threading import Thread
from Queue import Queue


class ConnectionMonitor(Thread):

    def __init__(self, ip, port, connections):
        self.ip=ip
        self.port=port
        self.connections=connections
        Thread.__init__(self)

    def run(self):

        sys.stdout.write("Running")
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((self.ip,self.port))
        s.listen(1)
        while 1:
            
            conn, addr = s.accept()
            print "connected to client @", addr
            self.connections.put(conn)
            conn.setblocking(0)

class ServerPipe(object):
    def __init__(self,ip,port):
       self.ip = ip
       self.port = port
       self.connections=Queue()
       
    def startConnection(self):
        sys.stdout.write("starting")
        self.cm=ConnectionMonitor(self.ip,self.port, self.connections)
        self.cm.start()
        sys.stdout.write("Connection started")

    def closeConnection(self):
        self.conn.close()

    def requestData(self, item):
        self.conn.send(item)    
        
if __name__ == "__main__":
    ip = "127.0.0.1"
    port = 1234
    if len(sys.argv)>1:
        port=int(sys.argv[1])
    sys.stdout.write("Beginning")
    sys.stdout.flush()
    p=ServerPipe(ip,port)
    sys.stdout.write("Starting outside")
    p.startConnection()
    while True:
        sys.stdout.flush()
        print "Connections:"
        for i in p.connections.queue:
            print i
        print data


        time.sleep(2)

    
    

#  LocalWords:  setblocking
